package com.ruoyi.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wechat.common.Constants;
import com.ruoyi.wechat.common.ServiceException;
import com.ruoyi.wechat.common.tree.TreeFactory;
import com.ruoyi.wechat.domain.*;
import com.ruoyi.wechat.domain.dto.ProductDTO;
import com.ruoyi.wechat.mapper.*;
import com.ruoyi.wechat.service.IAttachItemService;
import com.ruoyi.wechat.service.IProductService;
import com.ruoyi.wechat.service.ISpecService;
import com.ruoyi.wechat.utils.PageHelper;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务Service业务层处理
 *
 * @author YinHeng
 * @date 2024-01-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductParamMapper paramMapper;

    @Autowired
    private ProductCategoryMapper categoryMapper;

    @Autowired
    private ISpecService specService;

    @Autowired
    private ProductImgMapper imgMapper;

    @Autowired
    private ProductTagMapper tagMapper;

    @Autowired
    private IAttachItemService attachItemService;


    @Override
    public ProductDTO detail(Long id) {
        //商品信息
        LambdaQueryWrapper<Product> pQuery = new LambdaQueryWrapper<>();
        pQuery.eq(Product::getOnOffStatus, Constants.Product.ON_OFF_STATUS_1.getValue());
        pQuery.eq(Product::getStatus, Constants.Common.STATUS_1.getValue());
        pQuery.eq(Product::getId,id);
        Product product = this.getOne(pQuery);

        ProductDTO dto = new ProductDTO();
        BeanUtils.copyProperties(product, dto);
        dto.setTitle(product.getName());
        //商品规格
        LambdaQueryWrapper<Spec> specQuery = new LambdaQueryWrapper<>();
        specQuery.eq(Spec::getId, product.getSpecId());
        specQuery.eq(Spec::getItemId, product.getId());
        Spec spec = specService.getOne(specQuery);
        if (ObjectUtils.isEmpty(spec)) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "商品规格缺失");
        }
        //设置标签回显数据
        if (!ObjectUtils.isEmpty(spec.getTagIds())) {
            String[] splits = spec.getTagIds().split(",");
            List<Long> tagIdList = new ArrayList<>();
            for (String split : splits) {
                tagIdList.add(Long.parseLong(split));
            }
            List<ProductTag> tags = tagMapper.selectBatchIds(tagIdList);

            Map<Object, Object> tagMap = new HashMap<>();
            for (ProductTag tag : tags) {
                tagMap.put(tag.getAncestors(), tag.getId().toString());
            }
            spec.setTagMap(tagMap);
        }


        dto.setSpec(spec);
        //商品标签
        LambdaQueryWrapper<ProductTag> tagQuery = new LambdaQueryWrapper<>();
        tagQuery.eq(ProductTag::getItemId, product.getId());
        List<ProductTag> productTags = tagMapper.selectList(tagQuery);
        TreeFactory<Long, ProductTag> factory = new TreeFactory<>();
        List<ProductTag> tagTree = factory.buildTree(productTags);
        dto.setTagTree(tagTree);
        //商品图片
        LambdaQueryWrapper<ProductImg> imgQuery = new LambdaQueryWrapper<>();
        imgQuery.eq(ProductImg::getItemId, product.getId());
        List<ProductImg> imgList = imgMapper.selectList(imgQuery);
        dto.setImgList(imgList);
        //商品参数
        LambdaQueryWrapper<ProductParam> paramQuery = new LambdaQueryWrapper<>();
        paramQuery.eq(ProductParam::getItemId, product.getId());
        ProductParam param = paramMapper.selectOne(paramQuery);
        dto.setParam(param);
        //商品附加服务
        LambdaQueryWrapper<AttachItem> attachQuery = new LambdaQueryWrapper<>();
        attachQuery.eq(AttachItem::getItemId,dto.getId());
        attachQuery.eq(AttachItem::getEnable,Constants.Common.STATUS_1.getValue());
        attachQuery.eq(AttachItem::getType,Constants.AttachItem.TYPE_4.getValue());
        List<AttachItem> attachList = attachItemService.list(attachQuery);
        dto.setProductAttachList(attachList);
        //商品大类附加服务-预留
        return dto;
    }

    @Override
    public Page<ProductDTO> page(Product form) {
        //开始查询商品
        LambdaQueryWrapper<Product> goodsQuery = new LambdaQueryWrapper<>();
        goodsQuery.eq(com.ruoyi.wechat.domain.Product::getOnOffStatus, Constants.Product.ON_OFF_STATUS_1.getValue());
        goodsQuery.eq(com.ruoyi.wechat.domain.Product::getStatus, Constants.Common.STATUS_1.getValue());
//        goodsQuery.eq(!ObjectUtils.isEmpty(form.getCategory()), Product::getCategory, form.getCategory());
        goodsQuery.eq(!ObjectUtils.isEmpty(form.getType()),Product::getType,form.getType());
        goodsQuery.like(!ObjectUtils.isEmpty(form.getName()), Product::getName, form.getName());

        IPage<Product> page = new Page<>(PageHelper.getPageNum(), PageHelper.getPageSize());
        IPage<Product> pageList = this.page(page, goodsQuery);
        Page<ProductDTO> dtoPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());

        List<Product> records = pageList.getRecords();
        if (records.size() == 0) {
            return dtoPage;
        }
        List<Long> goodIds = new ArrayList<>();
        List<ProductDTO> dtoList = new ArrayList<>();
        for (Product product : records) {
            ProductDTO dto = new ProductDTO();
            BeanUtils.copyProperties(product, dto);
            dto.setTitle(product.getName());
            dtoList.add(dto);
            goodIds.add(product.getId());
        }

        //填充规格信息
        LambdaQueryWrapper<Spec> specQuery = new LambdaQueryWrapper<>();
        specQuery.in(Spec::getItemId, goodIds);
        List<Spec> specList = specService.list(specQuery);
        Map<Long, Spec> specMap = specList.stream().collect(Collectors.toMap(Spec::getId, Spec -> Spec));

        for (ProductDTO dto : dtoList) {
            Spec spec = specMap.get(dto.getSpecId());
            dto.setSpec(spec);
        }
        dtoPage.setRecords(dtoList);

        return dtoPage;
    }

    /**
     * 查询服务
     *
     * @param id 服务主键
     * @return 服务
     */
    @Override
    public Product selectTaskItemById(Long id) {
        return productMapper.selectById(id);
    }

    /**
     * 新增服务
     *
     * @param product 服务
     * @return 结果
     */
    @Override
    public int insertTaskItem(Product product) {
        return productMapper.insertTaskItem(product);
    }

    /**
     * 修改服务
     *
     * @param product 服务
     * @return 结果
     */
    @Override
    public int updateTaskItem(Product product) {
        return productMapper.updateTaskItem(product);
    }

    /**
     * 批量删除服务
     *
     * @param ids 需要删除的服务主键
     * @return 结果
     */
    @Override
    public int deleteTaskItemByIds(Long[] ids) {
        return productMapper.deleteTaskItemByIds(ids);
    }

    /**
     * 删除服务信息
     *
     * @param id 服务主键
     * @return 结果
     */
    @Override
    public int deleteTaskItemById(Long id) {
        return productMapper.deleteTaskItemById(id);
    }
}
